package com.winchain.chainbill.asset.biz.credit.rx;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.shell.bee.acct.transaction.po.AcctTxRec;
import com.shell.bee.persistence.transaction.Transaction;
import com.shell.bee.persistence.transaction.TransactionUtil;
import com.shell.framework.rx.OnErrorNotImplementedSubscriber;
import com.winchain.chainbill.ChainBillUtil;
import com.winchain.chainbill.bill.biz.send.rx.BatchBillEvent;
import com.winchain.chainbill.chain.ChainCallbackService;
import com.winchain.chainbill.trade.service.TradeService;

@Component
public class BillAssetTranSubscriber extends OnErrorNotImplementedSubscriber<BatchBillEvent<?, ?>> {
	@Autowired
	private TradeService tradeService;
	@Autowired
	private ChainCallbackService chainCallbackService;

	public void onApplicationEvent(final BatchBillEvent<?, ?> event) {
		if (!ChainBillUtil.onChain()) {
			return;
		}
		final List<AcctTxRec> acctTxRecs = (List) event.getValue("acctTxRecs");
		final String txSnHost;
		if ((acctTxRecs != null) && (acctTxRecs.size() > 0)) {
			try {
				TransactionUtil.execute(new Transaction() {
					public void doInTransaction() {
						Map<String, String> result = BillAssetTranSubscriber.this.tradeService.fire(null, acctTxRecs);
						event.setValue("txSnHost", result.get("tx_sn"));
					}
				}, new int[0]);
			} catch (Exception e) {
				e.printStackTrace();
				this.logger.error("chain trade error.");
				return;
			}
			txSnHost = (String) event.getValue("txSnHost");
			for (final AcctTxRec acctTxRec : acctTxRecs) {
				try {
					TransactionUtil.execute(new Transaction() {
						public void doInTransaction() {
							BillAssetTranSubscriber.this.chainCallbackService.callback(acctTxRec, txSnHost);
						}
					}, new int[0]);
				} catch (Exception e) {
					e.printStackTrace();
					this.logger.error("chain callback error.");
				}
			}
		}
	}
}
